import React, { useState, useMemo, useEffect, useRef } from 'react'
import { Toast, Input } from 'antd-mobile'
import { UpOutline, DownOutline } from 'antd-mobile-icons'
import Reading from './component/iReading'
import SliderConfirm from './component/slider'
import styles from './index.module.less'
import { getToken } from './service'
import { useNavigate } from 'react-router-dom'
// import { plantXWLog } from '@util/fun'

const phoneCodeArr = [
  { id: '86', text: '中国 (+86)' },
  { id: '852', text: '中国香港 (+852)' },
]
const phoneCodeMap = {
  '86': {
    length: 11,
    rule: /^1[3456789]\d{9}$/,
  },
  '852': {
    length: 8,
    rule: /^\d{8}$/,
  },
}

type refType = {
  setShowSliderContainer: (flag: boolean) => void
  sliderConfirm: (functionName: string, params: any) => void
}

function Login(props: { uuid: string }) {
  const { uuid } = props
  const navigate = useNavigate()
  const [phoneCode, setPhoneCode] = useState('86')
  const [telNumber, setTelNumber] = useState('')
  const [codeNumber, setCodeNumber] = useState('')
  const [codeText, setCodeType] = useState('获取验证码')
  const [codeShow, setCodeShow] = useState(false)
  const [checked, setChecked] = useState(false)
  const sliderRef = useRef<refType>(null)
  // const { type } = useActivityDetail(uuid)

  useEffect(() => {
    sdkInit()
    getPhone()
    document.title = '登录'
  }, [])

  const sdkInit = () => {
    const _data = {
      env: 'production', // 测试：sandbox， 线上：production
      entity: 2,
      loginout_callback: function (res: any) {
        console.log(res, '=== 未登录/登录失效统一处理回调方法 =======')
      },
    }
    /* eslint-disable */
    // @ts-ignore
    _data["client-id"] = 511205;
    /* eslint-disable */
    // @ts-ignore
    window.TAL_UC.rankConfig(_data);
    /* eslint-disable */
    // @ts-ignore
    window.TAL_UC.configNVC({
      renderToEle: "#captcha",
      isH5: true,
    });
  }

  // 手机号是否填写正确
  const isTelTrue = useMemo(() => {
    /* eslint-disable */
    // @ts-ignore
    if (telNumber.length === phoneCodeMap[phoneCode].length) return true
    return false
  }, [telNumber, phoneCode])

  // 手机号和验证码是否填写正确
  const isAllTrue = useMemo(() => {
    return isTelTrue && !!(codeNumber && codeNumber.length === 6)
  }, [isTelTrue, codeNumber])

  // 获取验证码
  const getSMSCode = () => {
    if (!isTelTrue) return false
    if (!(codeText === '获取验证码' || codeText === '重新发送')) return false
    /* eslint-disable */
    // @ts-ignore
    if (telNumber && !phoneCodeMap[phoneCode].rule.test(telNumber)) {
      Toast.show({ content: '请输入正确的手机号' })
      return false
    }
    Toast.show({ icon: 'loading', content: '加载中…', duration: 0 })

    const params = {
      data: {
        verify_type: 1,
        phone_code: phoneCode,
        phone: telNumber,
      },
      success: (res: { errcode: any; errmsg: any }) => {
        setPhone();
        Toast.clear()
        if (Number(res.errcode) === 0) {
          let total_micro_second = 60
          let timer = setInterval(function() {
            total_micro_second--
            if (total_micro_second <= 0) {
              clearInterval(timer)
              setCodeType('重新发送')
            } else {
              setCodeType(total_micro_second + 's后重新获取')
            }
          }, 1000)
          sliderRef.current!.setShowSliderContainer(false)
        } else if (Number(res.errcode) === 11021) {
          sliderRef.current!.setShowSliderContainer(true) // 打开 滑动验证弹窗
          sliderRef.current!.sliderConfirm("sendSMSCodeLogin", params); // 调取集团进行滑动验证的接口
        } else {
          sliderRef.current!.setShowSliderContainer(false)
          Toast.show({ content: res.errmsg })
          setCodeType('重新发送')
        }
      },
      fail: (res: { errmsg: any }) => {
        setCodeType('重新发送')
        Toast.show({ content: res.errmsg })
        Toast.clear()
      }
    };
    /* eslint-disable */
    // @ts-ignore
    window.TAL_UC.sendSMSCodeLogin(params);
  }

  // 进行登录，获取code
  const login = () => {
    if (!isAllTrue) return false
    if (!checked) {
      Toast.show({ content: '请勾选同意下方协议' })
      return false
    }
    const params = {
      data: {
        phone: telNumber,
        phone_code: phoneCode,
        sms_code: codeNumber,
      },
      success: (res: { errcode: any; data: { is_reg: any; code: any }; errmsg: any }) => {
        setPhone()
        if (Number(res.errcode) === 0) {
          sliderRef.current!.setShowSliderContainer(false)
          getTokenapi(res.data.code);
        } else if (Number(res.errcode) === 11021) {
          sliderRef.current!.setShowSliderContainer(true)
          sliderRef.current!.sliderConfirm("loginSms", params); // 调取集团进行滑动验证的接口
        } else {
          sliderRef.current!.setShowSliderContainer(false)
          Toast.show({ content: res.errmsg })
        }
      },
      fail: (error: any) => {
        console.log(error);
      },
      closeCaptchaCallback: function () {
        // 如果需要处理滑块加载失败后的图形验证码用户手动点击关闭时需要传递回调方法【1.11.02版本支持】
        console.log("关闭图形验证弹窗");
      },
    };
    /* eslint-disable */
    // @ts-ignore
    window.TAL_UC.loginSms(params);
  }

  // 集团验证码登录后还需要再次请求网校接口  https://api.xiwang.com/login/LoginV1/getToken
  const getTokenapi = (code: string) => {
    // var fromData = new FormData()
    // fromData.append("code", code)
    getToken({ code }).then((res: any) => {
      if (res.stat === 1) {
        // 登陆成功 路由跳转
        navigate(`/?uuid=${uuid}`)
        // plantXWLog('click_0mHhMf93', {sgroupid: uuid, userid: res.data.user_info.user_id || ''})
      }
    })
    .catch(() => {
      // console.log(res, "查看数据");
    })
  }

  // 出现切换区号下拉
  const toShow = (e: { stopPropagation: () => void }) => {
    e.stopPropagation()
    setCodeShow(!codeShow)
  }

  // 关闭切换区号下拉
  const toClose = () => {
    setCodeShow(false)
  }

  // 切换区号
  const onSelect = (action: { id: any; text?: string }) => {
    setPhoneCode(action.id)
    setCodeShow(!codeShow)
  }

  // 手机号输入
  const telChange = (num: React.SetStateAction<string>) => {
    setTelNumber(num)
  }

  // 验证码输入
  const codeChange = (num: React.SetStateAction<string>) => {
    setCodeNumber(num)
  }

  const getPhone = () => {
    setPhoneCode(localStorage.getItem('phone_code') || '86')
    setTelNumber(localStorage.getItem('phone') || '')
  }

  const setPhone = () => {
    localStorage.setItem('phone_code', phoneCode)
    localStorage.setItem('phone', telNumber)
  }

  return (
    <div
      className={styles['p-login']}
      onClick={() => {
        toClose()
      }}
    >
      <div className={styles['title']}>验证码登录</div>
      <div className={styles['login-container']}>
        <div className={styles['login-input']}>
          <div className={styles['phone-input']}>
            <div className={styles['phone-code']}>
              <span
                onClick={(e: { stopPropagation: () => void }) => {
                  toShow(e)
                }}
              >
                <span>+{phoneCode}</span>
                {codeShow ? (
                  <UpOutline className={styles['up-down']} />
                ) : (
                  <DownOutline className={styles['up-down']} />
                )}
              </span>
              {codeShow && <div className={styles['triangle']}></div>}
              {codeShow && (
                <div className={styles['phone-code-popup']}>
                  <span className={styles['solid']}></span>
                  {phoneCodeArr.map(item => {
                    return (
                      <span
                        className={styles['phone-code-popup-span']}
                        onClick={() => {
                          onSelect(item)
                        }}
                        key={item.id}
                      >
                        {item.text}
                      </span>
                    )
                  })}
                </div>
              )}
            </div>
            <Input
              type="number"
              className={styles['tel-input']}
              style={{ '--font-size': '14px' }}
              placeholder="请输入手机号"
              value={telNumber}
              onChange={e => {
                const a = e.substring(0,11)
                telChange(a)
              }}
            />
          </div>
          <div className={styles['code-wrapper']}>
            <Input
              type="number"
              style={{ '--font-size': '14px' }}
              placeholder="请输入验证码"
              value={codeNumber}
              onChange={e => {
                const a = e.substring(0,6)
                codeChange(a)
              }}
            />
            <div
              className={`${styles['code-btn']} ${isTelTrue ? styles['code-ok'] : ''}`}
              onClick={() => {
                getSMSCode()
              }}
            >
              {codeText}
            </div>
          </div>
          <SliderConfirm ref={sliderRef} />
        </div>
        <div
          className={`${styles['submit-btn']} ${isAllTrue ? styles['submit-ok'] : ''}`}
          onClick={() => {
            login()
          }}
        >
          登录/同意协议并注册
        </div>
      </div>
      <Reading setChecked={setChecked} uuid={uuid} ></Reading>
    </div>
  )
}

export default  Login;